package com.piece.core.framework.util.net;

import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.time.DateUtil;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.framework.util.basic.SpringUtil;
import com.piece.core.framework.properties.ApplicationProperties;
import lombok.Setter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 节假日查询工具
 */
@Setter
public class FestivalUtil {

    private static final ReentrantLock lock = new ReentrantLock();

    private String url;

    private static FestivalUtil instance;

    public static FestivalUtil getInstance() {
        if (null == instance) {
            lock.lock();
            if (null == instance) {
                instance = new FestivalUtil();
                ApplicationProperties properties = SpringUtil.getBean(ApplicationProperties.class);
                instance.setUrl(properties.getFestivalUrl());
            }
            lock.unlock();
        }
        return instance;
    }

    /**
     * 查询指定月份节假日数据
     * <p>工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2</p>
     *
     * @param time 日期数组,格式:yyyyMM ','分隔的数组
     * @return [{日期,结果}, {日期,结果}...]
     */
    public AjaxResponse festivalOfMonth(String time) {
        Map<String, String> param = new HashMap<>();
        param.put("m", time);
        return HttpUtil.get(this.url).form(param).execute().response();
    }

    /**
     * 是否是工作时间
     *
     * @param date
     */
    public boolean isWorkDay(Date date) {
        return "0".equals(getDayType(date));
    }

    /**
     * 是否是工作时间
     *
     * @param date
     */
    public boolean isWeekend(Date date) {
        return "1".equals(getDayType(date));
    }

    /**
     * 是否是工作时间
     *
     * @param date
     */
    public boolean isFestival(Date date) {
        return "2".equals(getDayType(date));
    }

    /**
     * 获取时间类型
     *
     * @param date
     * @return 工作日 0, 休息日 1, 节假日 2
     */
    public String getDayType(Date date) {
        Map<String, String> param = new HashMap<>();
        String formatDate = DateUtil.formatDate(date, "yyyyMMdd");
        param.put("d", formatDate);
        AjaxResponse ajaxResult = HttpUtil.get(this.url).form(param).execute().response();
        if (ajaxResult.isSuccess()) {
            Map map = JsonUtil.toMap((String) ajaxResult.getParam());
            return (String) map.get("formatDate");
        }

        return null;
    }
}
